// uniCloud/cloudfunctions/callBlueLM/index.js
'use strict';
const crypto = require('crypto'); // 用于签名算法（需自行实现）

// 1. 初始化配置（建议通过云函数环境变量配置）
// const APP_ID = process.env.BLUELM_APP_ID || '2025579665';
// const APP_KEY = process.env.BLUELM_APP_KEY || 'DWaLmGYeXmNGggPa';
// const API_URL = 'https://api-ai.vivo.com.cn/vivogpt/completions';
const APP_ID = '2025579665';
const APP_KEY ='DWaLmGYeXmNGggPa';
const API_URL = 'https://api-ai.vivo.com.cn/vivogpt/completions';

// 生成随机字符串
function generateRandomString(len) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  let result = '';
  for (let i = 0; i < len; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 生成规范化查询字符串
function generateCanonicalQueryString(queryParams) {
  if (!queryParams) return '';
  const params = {};
  queryParams.split('&').forEach(item => {
    const [key, value = ''] = item.split('=');
    params[key] = value;
  });
  const keys = Object.keys(params).sort();
  return keys.map(key =>
    encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
  ).join('&');
}

// 生成签名
function generateSignature(appKey, signingString) {
  return crypto.createHmac('sha256', appKey)
    .update(signingString)
    .digest('base64');
}

// 生成鉴权请求头
function genSignHeaders(appId, appKey, method, uri, queryParams) {
  const nonce = generateRandomString(8);
  const timestamp = Math.floor(Date.now() / 1000).toString(); // 秒级时间戳
  const canonical_query_string = generateCanonicalQueryString(queryParams);
  const signed_headers_string =
    `x-ai-gateway-app-id:${appId}\n` +
    `x-ai-gateway-timestamp:${timestamp}\n` +
    `x-ai-gateway-nonce:${nonce}`;
  const fields = [
    method,
    uri,
    canonical_query_string,
    appId,
    timestamp,
    signed_headers_string
  ];
  const buf = fields.join('\n');
  return {
    'X-AI-GATEWAY-APP-ID': appId,
    'X-AI-GATEWAY-TIMESTAMP': timestamp,
    'X-AI-GATEWAY-NONCE': nonce,
    'X-AI-GATEWAY-SIGNED-HEADERS': 'x-ai-gateway-app-id;x-ai-gateway-timestamp;x-ai-gateway-nonce',
    'X-AI-GATEWAY-SIGNATURE': generateSignature(appKey, buf)
  };
}

// 2. 主函数（标准云函数入口）
exports.main = async (event, context) => {
  try {
    // 参数校验
    const { prompt, sessionId, messages } = event;
    if ((!prompt || prompt.trim() === '') && (!messages || !Array.isArray(messages) || messages.length === 0)) {
      return { code: 400, message: 'prompt和messages不能同时为空' };
    }

    // 3. 生成请求参数
    const requestId = generateUUID();
    const finalSessionId = sessionId || generateUUID();
    
    const requestData = {
      model: 'vivo-BlueLM-TB-Pro',
      sessionId: finalSessionId,
      extra: {
        temperature: 0.9,
        max_new_tokens: 2048,
      }
    };
    if (prompt && prompt.trim() !== '') requestData.prompt = prompt;
    if (messages && Array.isArray(messages) && messages.length > 0) requestData.messages = messages;

    // 4. 生成签名请求头（需自行实现）
    const headers = genSignHeaders(APP_ID, APP_KEY, 'POST', '/vivogpt/completions', `requestId=${requestId}`);
    headers['Content-Type'] = 'application/json';

    // 5. 拼接带 requestId 的 URL
    const apiUrlWithRequestId = `${API_URL}?requestId=${requestId}`;

    // 6. 使用uniCloud.httpclient发起请求[3,6](@ref)
    const res = await uniCloud.httpclient.request(apiUrlWithRequestId,{
      method: 'POST',
      data: requestData,
      headers,
      dataType: 'json', // 自动解析JSON响应
      contentType: 'json', // 自动序列化请求体
    });

    // 6. 处理响应
    if (res.status === 200 && res.data.code === 0) {
      return {
        code: 0,
        data: res.data.data.content,
        sessionId: finalSessionId // 返回新生成的sessionId
      };
    } else {
      console.error('API Error:', res.data);
      // 返回详细错误信息
      return { code: res.data.code || 500, message: JSON.stringify(res.data) };
    }
  } catch (err) {
    console.error('Request Failed:', err);
    return { code: 500, message: err.message };
  }
};

// 辅助函数（生成UUID）
function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
  });
}